<template>
  <div class="upload-container">
    <el-button :loading="loading" class="upload-btn">
      <input @change="handleUpload" class="file-input" type="file" name="file" accept="image/*" />
      上传
    </el-button>
    <el-progress v-show="showProgress" class="progress" :status="status" :percentage="progress"></el-progress>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Upload",
  props: [],
  data() {
    return {
      progress: 0,
      status: null,
      loading: false,
      showProgress: false
    };
  },
  watch: {
    progress(val) {
      if (val == 100) {
        this.status = "success";
      }
    }
  },
  methods: {
    handleUpload(file) {
      const that = this;
      if (file.target.files[0]) {
        var form = new FormData();
        form.append("file", file.target.files[0]);
        this.progress = 0;
        this.status = null;
        this.showProgress = true;
        this.loading = true;
        this.$emit("beforeUpload", this.loading);
        request({
          url: "/pc/file/upload",
          method: "post",
          upload: form,
          onUploadProgress: function(progressEvent) {
            // 对原生进度事件的处理
            if (progressEvent.lengthComputable) {
              that.progress = parseInt(((progressEvent.loaded / progressEvent.total) * 100).toFixed(0));
            }
          }
        })
          .then(res => {
            this.loading = false;
            this.$emit("res", res);
          })
          .catch(err => {
            this.loading = false;
          });
      }
    }
  },
  created() {}
};
</script>

<style lang="scss" scoped>
.upload-container {
  display: flex;
  flex-direction: row;
  align-items: center;

  .progress {
    width: 200px;
    margin-left: 20px;
  }

  .upload-btn {
    position: relative;
    overflow: hidden;
  }

  .file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
    height: 200px;
    opacity: 0;
    // visibility: hidden;
  }
}
</style>
